import Taro, { useDidShow } from '@tarojs/taro'
import React, { useEffect, useMemo, useState, useCallback } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { ScrollView, View } from '@tarojs/components'
import NavCardItem from '@COMPONENTS/Profile/NavCardItem'
import HorizontalNavItem from '@COMPONENTS/Profile/HorizontalNavItem'
import ProfileHeader from '@COMPONENTS/Profile/ProfileHeader'
import ConsultationCarousel from '@COMPONENTS/Consultation/ConsultationCarousel'
import withNoInternet from '@HOC/withNoInternet'
import i18n from '@I18N'
import { NAV_TYPE_ENUM } from '@CONSTANTS/profile'
import Images from '@ASSET/Images'
import messageActions from '@ACTIONS/message'
import patientActions from '@ACTIONS/patient'
import servicePackAction from '@ACTIONS/servicePack'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { getWindowHeight, convertPx, getPlatform, getRouterValue } from '@UTILS/common'
import { RootStateITF } from '@REDUXITF/index'
import { PatientITF } from '@INTERFACES/Patient'
import { ServicePackITF } from '@INTERFACES/ServicePackITF'
import { MessageStateITF } from '@REDUXITF/message'
import { RouterConfigITF } from '@INTERFACES/Profile'
import { ConsultationDataITF } from '@INTERFACES/SmartAssistant'
import { getGlobalData } from '@UTILS/globalData'
import DBConfig from '@CONFIG/DBConfig'
import style from './index.module.scss'

const { isWeb } = getPlatform()

interface RouterOptionsITF {
  PatientId: string
  isVisitor: boolean
  message: MessageStateITF
  isDisabledConsultation: boolean
  orderPacks: ServicePackITF[]
  isTakeda: boolean
}

const getRouterOptions = ({
  PatientId, isVisitor, message, isDisabledConsultation, orderPacks, isTakeda
}: RouterOptionsITF) => {
  const horizontalRoute : RouterConfigITF[] = [{
    route: 'messageList',
    name: i18n.profile.my_messages(),
    eventId: Analytic_Type.num_my_message.eventId,
    source: Images.profile.my_message_new,
    num: isVisitor ? 0 : message.newAlertNum + message.newChatMessageCount
  },
  {
    route: 'orderList',
    isYellow: true,
    name: i18n.profile.my_orders(),
    eventId: Analytic_Type.num_my_order.eventId,
    source: Images.profile.my_order_new
  }]

  const verticalRoute: RouterConfigITF[] = [
    {
      route: PatientId ? 'patientDetail' : 'createPatient',
      routeParams: PatientId ? { p8Id: PatientId } : {},
      name: i18n.profile.patient_message(),
      eventId: Analytic_Type.num_my_patient.eventId,
      source: Images.profile.health_records,
      num: isVisitor ? 0 : message.unViewedConsulReportCount
    }]

  verticalRoute.push({
    route: 'consulCouponList',
    name: i18n.coupon.pic_coupon_card(),
    eventId: Analytic_Type.num_coupon_card.eventId,
    source: Images.profile.coupon_card
  })

  const isShowPack = DBConfig.careEnvType !== 'prod' && !isDisabledConsultation
  isShowPack && !isTakeda && verticalRoute.push({
    route: 'myServicePack',
    name: i18n.profile.my_service_pack(),
    eventId: Analytic_Type.num_my_service_pack.eventId,
    source: Images.servicePack.my_service_pack,
    disabledVerify: true
  })
  !isVisitor && !isTakeda && Array.isArray(orderPacks) && orderPacks.length && verticalRoute.push({
    route: 'myOrderServicePack',
    name: i18n.profile.my_order_pack(),
    eventId: Analytic_Type.num_my_order_pack.eventId,
    source: Images.servicePack.my_order_pack
  })
  verticalRoute.push({
    route: '',
    name: i18n.profile.connect_customer_service(),
    eventId: Analytic_Type.num_my_customer.eventId,
    source: Images.profile.connect_customer_service,
    type: NAV_TYPE_ENUM.Button
  })
  verticalRoute.push({
    route: 'agreement',
    name: i18n.profile.agreement(),
    eventId: Analytic_Type.tap_agreement.eventId,
    source: Images.profile.agreement,
    disabledVerify: true
  })
  verticalRoute.push({
    route: 'policy',
    name: i18n.profile.policy(),
    eventId: Analytic_Type.tap_policy.eventId,
    source: Images.profile.policy,
    disabledVerify: true
  })
  return {
    horizontalRoute,
    verticalRoute
  }
}

const Index = () => {
  const language = 'zh'
  const [refreshing, setRefreshing] = useState(false)
  const heightStyle = { height: convertPx(getWindowHeight(isWeb)) }
  const dispatch = useDispatch()
  const { dispatchSetTabBarBadge, dispatchGetNewBellAlertsNumber, dispatchGetUnViewedConsultationReport } = messageActions
  const { dispatchGetDefaultPatient, dispatchGetMyConsultations } = patientActions
  const { dispatchGetOrderPacks } = servicePackAction

  const isVisitor = useSelector<RootStateITF, boolean>(state => state.profile.isVisitor)
  const orderPacks = useSelector<RootStateITF, ServicePackITF[]>(state => state.servicePack.orderPacks)
  const defaultPatient = useSelector<RootStateITF, PatientITF>(state => state.patient.defaultPatient)
  const myConsultations = useSelector<RootStateITF, ConsultationDataITF>(state => state.patient.myConsultationsWithTotal)
  const isDisabledConsultation = useSelector<RootStateITF, boolean>(state => state.auth.isDisabledConsultation)
  const message = useSelector<RootStateITF, MessageStateITF>(state => state.message)
  const acquireChannel = useMemo(() => getRouterValue('AcquireChannel'), [])
  const { PatientId } = defaultPatient || {}
  const isTakeda = useMemo(() => (isWeb && (getGlobalData('isTakeda') || acquireChannel === 'takeda')), [acquireChannel])

  const { horizontalRoute, verticalRoute } = useMemo(
    () => getRouterOptions({
      PatientId, isVisitor, message, isDisabledConsultation, orderPacks, isTakeda
    }),
    [PatientId, isVisitor, message, isDisabledConsultation, orderPacks, isTakeda]
  )

  const onRefresh = async () => {
    try {
      setRefreshing(true)
      await fetchData()
    } catch (error) {
      Taro.showToast({
        title: error.message || error,
        icon: 'none'
      })
    } finally {
      setRefreshing(false)
    }
  }

  const fetchData = useCallback(
    async () => {
      try {
        if (isVisitor) return
        dispatch(dispatchGetDefaultPatient())
        dispatch(dispatchGetOrderPacks({ skip: 0 }))
        dispatch(dispatchGetMyConsultations())
        dispatch(dispatchGetNewBellAlertsNumber())
        dispatch(dispatchGetUnViewedConsultationReport())
      } catch (error) {
        Taro.showToast({
          title: error.message || error,
          icon: 'none'
        })
      }
    },
    [isVisitor, dispatch, dispatchGetDefaultPatient, dispatchGetOrderPacks,
      dispatchGetMyConsultations, dispatchGetNewBellAlertsNumber, dispatchGetUnViewedConsultationReport]
  )

  useDidShow(() => {
    Taro.eventCenter.trigger('CheckMsgConnect')
    fetchData()
    dispatch(dispatchSetTabBarBadge())
  })

  useEffect(() => {
    fetchData()
  }, [fetchData])

  return (
    <View className={style.container} style={heightStyle}>
      <ScrollView
        onRefresherRefresh={onRefresh}
        refresherTriggered={refreshing}
        refresherEnabled
        refresherBackground="#EBF8F3"
        refresherDefaultStyle="black"
        scrollY
        style={heightStyle}
      >
        <ProfileHeader language={language} />
        {!isTakeda && (
          <View className={style.horizontalRouteView}>
            {horizontalRoute.map(item => (
              <HorizontalNavItem data={item} key={item?.route} isLogin={!isVisitor} />
            ))}
          </View>
        )}
        {!isDisabledConsultation && (
          <ConsultationCarousel language={language} myConsultationsWithTotal={myConsultations} />
        )}
        <View className={style.verticalRouteBox}>
          {verticalRoute.map(item => (
            <NavCardItem data={item} key={item?.route + item.eventId} isLogin={!isVisitor} showRightText={item.showRightText} />
          ))}
        </View>
      </ScrollView>
    </View>
  )
}

export default withNoInternet(Index)
